/*
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "interface/network_port/link_info.h"
#include <mc/log.h>

namespace dev {

bool NetworkPort_LinkInfo::update_link_status_by_ncsi(uint8_t port_id) {
    ncsi_link_status_info_t link_status = {};
    bool ret = m_ncsi_over_mctp_wx->get_link_status(DEFAULT_PACKAGE_ID, port_id, &link_status);
    if (!ret) {
        elog("Error: Failed to update link status");
        LinkStatus.set_value(255);  // 无效值
        SpeedMbps.set_value(0);
        FullDuplex.set_value(false);
        return false;
    }
    // link_status 已经是数值类型：0-DOWN, 1-UP, 255-无效值
    LinkStatus.set_value(link_status.link_status);
    SpeedMbps.set_value(link_status.speed_mbps);
    FullDuplex.set_value(link_status.full_duplex ? true : false);
    return true;
}

void NetworkPort_LinkInfo::start_ncsi_update_task_wx(ncsi_over_mctp_wx_ptr ncsi_over_mctp,
                                                     mc::milliseconds interval, uint8_t port_id) {
    m_ncsi_over_mctp_wx = ncsi_over_mctp;
    m_ncsi_timer        = new mc::core::timer(this);
    m_ncsi_timer->timeout.connect([this, port_id]() {
        update_link_status_by_ncsi(port_id);
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void NetworkPort_LinkInfo::stop_ncsi_update_task() {
    m_ncsi_timer->stop();
}
} // namespace dev

MC_REFLECT(dev::NetworkPort_LinkInfo)